using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.ProcessManagement;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ProcessManagements;
using System.Transactions;

namespace RBAC.Write.Api.Application.Handler.ProcessManagements
{
    /// <summary>
    /// 新增工序分类 处理器
    /// </summary>
    public class AddProcessClassificationHandler : IRequestHandler<AddProcessClassificationCommand, APIResult<int>>
    {
        private readonly IBaseRepository<ProcessClassification> repository;
        private readonly ILogger<AddProcessClassificationHandler> logger;

        public AddProcessClassificationHandler(
            IBaseRepository<ProcessClassification> repository,
            ILogger<AddProcessClassificationHandler> logger)
        {
            this.repository = repository;
            this.logger = logger;
        }

        public Task<APIResult<int>> Handle(AddProcessClassificationCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            try
            {
                // 1. 基础校验
                if (string.IsNullOrWhiteSpace(request.ClassificationCode))
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "工序分类编号不能为空";
                    return Task.FromResult(res);
                }
                if (string.IsNullOrWhiteSpace(request.ClassificationName))
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "工序分类名称不能为空";
                    return Task.FromResult(res);
                }
                if (request.Status != 0 && request.Status != 1)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "状态只能是0(禁用)或1(启用)";
                    return Task.FromResult(res);
                }

                // 2. 重复校验（编号、名称）
                var dupCode = repository.QueryFirstOrDefault<int>(
                    "SELECT COUNT(1) FROM ProcessClassification WHERE ClassificationCode = @ClassificationCode AND IsDeleted = false",
                    new { request.ClassificationCode });
                if (dupCode > 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "工序分类编号已存在";
                    return Task.FromResult(res);
                }

                var dupName = repository.QueryFirstOrDefault<int>(
                    "SELECT COUNT(1) FROM ProcessClassification WHERE ClassificationName = @ClassificationName AND IsDeleted = false",
                    new { request.ClassificationName });
                if (dupName > 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "工序分类名称已存在";
                    return Task.FromResult(res);
                }

                using (var scope = new TransactionScope())
                {
                    // 3. 插入数据（自定义SQL，保持与现有风格一致）
                    var sql = @"INSERT INTO ProcessClassification 
                                (ClassificationCode, ClassificationName, Sort, Status, Remark, CreateTime, CreateUser, IsDeleted)
                                VALUES (@ClassificationCode, @ClassificationName, @Sort, @Status, @Remark, @CreateTime, @CreateUser, @IsDeleted);
                                SELECT LAST_INSERT_ID();";

                    var now = DateTime.Now;
                    var id = repository.QueryFirstOrDefault<int>(sql, new
                    {
                        request.ClassificationCode,
                        request.ClassificationName,
                        Sort = request.Sort,
                        Status = request.Status,
                        Remark = request.Remark,
                        CreateTime = now,
                        CreateUser = "system",
                        IsDeleted = false
                    });

                    scope.Complete();

                    if (id <= 0)
                    {
                        res.Code = APIEnums.Error;
                        res.Msg = "新增失败";
                        return Task.FromResult(res);
                    }

                    res.Code = APIEnums.Success;
                    res.Data = id;
                    res.Msg = "新增成功";
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "新增工序分类失败: {Message}", ex.Message);
                res.Code = APIEnums.Error;
                res.Msg = "新增工序分类异常";
                res.Data = 0;
            }

            return Task.FromResult(res);
        }
    }
}
